package com.wdb007.venus.web.api.handler;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wdb.exchange.constant.SourceEnum;
import com.wdb.exchange.model.Event;
import com.wdb007.venus.web.api.config.AmqpConfig;

@Component
public class AmqpHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final String topicPrefix = "/ibms/";   // mqtt uses '/' as separator, it will be map to '.' in amqp.

    @Autowired
    String serverId;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    BookcaseHandler bookcaseHandler;

    @Autowired
    private ApiListenHandler apiListenHandler;
    
    @RabbitListener(queues = AmqpConfig.SERVER_QUEUE_NAME, containerFactory = "aRabbitListenerContainerFactory")
    public void processMessage(@Payload byte[] message) {
        String msgstr = new String(message, Charset.forName("UTF-8"));

        logger.info("processMessage {}", msgstr);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> result = objectMapper.readValue(msgstr, Map.class);

            bookcaseHandler.process(result);
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @RabbitListener(queues = AmqpConfig.WILL_MESSAGE_QUEUE_NAME, containerFactory = "aRabbitListenerContainerFactory")
    public void processWillMessage(@Payload byte[] message) {
        String msgstr = new String(message, Charset.forName("UTF-8"));
        logger.info("processWillMessage {}", msgstr);
    }

    @RabbitListener(queues = AmqpConfig.DEADLETTER_QUEUE_NAME, containerFactory = "aRabbitListenerContainerFactory")
    public void processDeadLetterMessage(@Payload byte[] message) {
        String msgstr = new String(message, Charset.forName("UTF-8"));
        logger.info("processDeadLetterMessage {}", msgstr);
    }

    @RabbitListener(queues = AmqpConfig.API_SERVICE_QUEUE_NAME, containerFactory = "bRabbitListenerContainerFactory")
    public void processServiceMessage(@Payload byte[] message) {
        try {
        		String msgstr = new String(message, Charset.forName("UTF-8"));
            logger.info("processServiceMessage {}", msgstr);
            Event event = Event.fromJson(msgstr);
            if(!SourceEnum.API.equals(event.source)){
            		apiListenHandler.process(event);
            }
            
        }catch(Exception e) {
        		logger.error(e.getMessage());
        }
    		
        
    }

    public void publish(String topic, String msg) {
        final String routeKey = topic.replaceAll("/", ".");
        sendTopic(routeKey, msg);
    }

    public void publish(String did, Map<String, Object> msg) {
        if (msg.getOrDefault("sid", null) == null) {
            msg.put("sid", serverId);
        }
        msg.put("did",  did);
        msg.put("chan", "mqtt");
        msg.put("ts",   new Date().getTime());
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String msgstr = objectMapper.writeValueAsString(msg);
            publish(topicPrefix + did, msgstr);
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public void sendTopic(String routineKey, String msg) {
        logger.debug("sendTopic: " + routineKey + " " + msg);
        try {
            MessageProperties props = new MessageProperties();
            Message message = new Message(msg.getBytes(Charset.forName("UTF-8")), props);
            //rabbitTemplate.convertAndSend(AmqpConfig.TOPIC_EXCHANGE, routineKey, msg.getBytes(Charset.forName("UTF-8")));
            rabbitTemplate.convertAndSend(AmqpConfig.TOPIC_EXCHANGE, routineKey, message);
        }
        catch (AmqpException e) {
            logger.error(e.getMessage());
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public void sendFanout(String exchange, String msg) {
        logger.debug("sendFanout: " + exchange + " " + msg);
        try {
            MessageProperties props = new MessageProperties();
            Message message = new Message(msg.getBytes(Charset.forName("UTF-8")), props);
            rabbitTemplate.convertAndSend(exchange, "", message);
        }
        catch (AmqpException e) {
            logger.error(e.getMessage());
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}

